import React from 'react';
import logo from '@/assets/icons/ai-agent1.svg';
import aiaalogo from '@/assets/images/aiaaLogo.png';

import { SvgIcon } from '@/components/icon';
import { getFilenameFromPath } from '@/utils/common';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { DEFAULT_IMAGES, CUSTOM_IMAGES } from './ImageDisplay';

interface AvatarDisplayProps {
  src?: string;
  className?: string;
  size?: number;
  imgType?: string;
}

/**
 * 应用头像展示组件
 * @param appLogo 应用logo的base64字符串或URL
 * @param className 额外的样式类名
 */
const AvatarDisplay: React.FC<AvatarDisplayProps> = ({
  src,
  className = 'h-[50px] w-[50px]',
  size = 40,
  imgType = 'round',
}) => {
  const { special_app_lable } = useOrchestrationStore();
  // 判断是否为base64格式
  const isBase64 = (str: string): boolean => {
    try {
      // 基本判断：base64字符串通常由A-Z、a-z、0-9、+、/、=组成
      return /^[A-Za-z0-9+/=]+$/.test(str);
    } catch (e) {
      return false;
    }
  };

  const isSvg = (str: string): boolean => {
    return str?.endsWith('.svg');
  };

  // 获取图片源
  const getImageSrc = (logo: string): string => {
    if (!logo || Object.keys(DEFAULT_IMAGES).includes(logo)) return DEFAULT_IMAGES[logo] || logo;
    if (!logo || Object.keys(CUSTOM_IMAGES).includes(logo)) return CUSTOM_IMAGES[logo] || logo;

    if (!logo || logo === 'aiaalogo') return aiaalogo;

    // 判断是否已经是完整URL（以http或https开头）
    if (logo.startsWith('http://') || logo.startsWith('https://')) {
      return logo;
    }

    // 判断是否为base64格式
    if (isBase64(logo)) {
      return `data:image/png;base64,${logo}`;
    }

    // 默认当作URL返回
    return logo;
  };

  return (
    <>
      {isSvg(src!) ? (
        <div className={`flex flex-shrink-0 items-center text-center leading-[50px] ${className}`}>
          <SvgIcon
            icon={getFilenameFromPath(src!).replace('.svg', '').replace('.svg', '')}
            size={size}
          />
        </div>
      ) : (
        <div className={`flex-shrink-0 ${className}`}>
          {src && src !== 'default' ? (
            <img
              src={getImageSrc(src)}
              className={`h-full w-full object-cover ${
                imgType === 'round' ? 'rounded-[50%]' : 'rounded-small'
              }`}
              alt="app logo"
              onError={(e) => {
                e.currentTarget.src = logo;
              }}
            />
          ) : (
            <img
              src={logo}
              className="h-full w-full object-cover"
              alt="default logo"
              onError={(e) => {
                e.currentTarget.src = logo;
              }}
            />
          )}
        </div>
      )}
    </>
  );
};

export default AvatarDisplay;
